package match

import (
	mc "bbtradeByGo/model/match"
	rmc "bbtradeByGo/model/match/model"
	"bbtradeByGo/pkg/email"
	"bbtradeByGo/pkg/gredis"
	"bbtradeByGo/pkg/logging"
	"bbtradeByGo/service/match/purchase"
	"bbtradeByGo/service/match/sale"
	"fmt"
	"github.com/gomodule/redigo/redis"
)


//CancelPush 取消订单
func CancelPush() {
	//获取currency match 匹配到的值
	OrderCancel()
}

// OrderPlace 同步订单
func OrderPlace(){
	//1.获取同步到的id
	id, err := redis.Int(gredis.HGet("currency:match:config", "orderPlace"))
	if err != nil{
		email.SendMail("service.match.OrderPlace err1", err.Error())
		logging.Error("service.match.OrderPlace err1: ",err)
	}
	//2.一次同步1000，获取订单
	mOrderList, err := mc.OrderList(&rmc.MCondition{
		PageNo: 1,
		PageSize: 1000,
		IdGt: id,
		OrderIn: 1,
	})

	if err != nil {
		email.SendMail("service.match.OrderPlace err2 ", err.Error())
		logging.Error("service.match.OrderPlace err2: ",err)
	}

	if len(mOrderList) > 0 {
		for _, v := range mOrderList{
			switch v.Type{
			    case 0:
                    sale.Sale(v)
			    case 1:
			    	purchase.PurChase(v)
			}
		}
		length := len(mOrderList) - 1
		val  := mOrderList[length].Id
		gredis.HSet("currency:match:config", "orderPlace", val)
	}
}

//OrderCancel 用户取消订单同步，php取消订单的同时，也要将取消订单好放入到此队列中
func OrderCancel() {
	//1.获取同步到的id
	id, err := redis.Int(gredis.HGet("currency:match:config", "orderCancel"))

	if err != nil {
		email.SendMail("service.match.match.OrderCancel", err.Error())
		logging.Error("service.match.match.OrderCancel err:", err)
	}

	//2.一次同步100
	mCondition, err := mc.OrderList(&rmc.MCondition{
		PageNo: 1,
		PageSize: 10,
		IdGt: id,
		OrderStatus: 3,
	})

	if len(mCondition) > 0 {
		for _, v := range mCondition {
			key := fmt.Sprintf("currency:match:cancel:%d/%d", v.BaseCurrencyId, v.CurrencyId)
			gredis.LPush(key, v.Id)
		}
		length := len(mCondition) - 1
		val  := mCondition[length].Id
		gredis.HSet("currency:match:config", "orderCancel", val)
	}
}

